﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Permissions;
using System.Text;

namespace Kugar.Core.Security
{
    class PermissionAuthorizeAttribute
    {
    }

    public class TestPermissionAttribute : CodeAccessSecurityAttribute
    {
        public TestPermissionAttribute(SecurityAction action)
            : base(action)
        {
            //Role = role;
        }

        public string Role { set; get; }

        public override IPermission CreatePermission()
        {
            return new TestPermission(Role);
        }

    }

    public class TestPermission : CodeAccessPermission, IUnrestrictedPermission
    {
        private string _role = null;

        public TestPermission(string role)
        {

            _role = role;

            base.Demand();
        }

        public override SecurityElement ToXml()
        {
            var t = new SecurityElement("Kugar");

            t.AddAttribute("Test", _role);

            return t;
        }

        public override void FromXml(SecurityElement elem)
        {
            var role = elem.Attributes["Test"].ToString();

            this._role = role;
        }

        public override IPermission Copy()
        {
            return new TestPermission(_role);
        }

        public string Role { get { return _role; } }

        public override IPermission Intersect(IPermission target)
        {
            return new TestPermission("");
        }

        public override bool IsSubsetOf(IPermission target)
        {
            //TODO:如果target为空,则判断当前用户是否包含Role权限,如果包含,返回true,如果不包含,抛出错误
            //如果target不为空,则检查当前用户是否包含target.role的权限,并且不抛出错误

            if (target is TestPermission)
            {
                return ((TestPermission)target).Role == "";

            }
            else
            {
                throw new SecurityException();

                return false;
            }
        }

        public bool IsUnrestricted()
        {
            return false;
        }
    }
}
